// pages/buyLimit/buyLimit.js
//更多限时抢购
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let user_js = require("../../utils/user.js");
let sys_js = require("../../utils/system.js");
let cart_js = require("../../utils/cart.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");
let page_js = require("../../utils/pageOptions.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sysInfo: null,
    userInfo: null,
    pageScrollTop: 0,
    containerTouchmove: '',
    contentStatus: -1,
    selectedInfo: {
      index: 0,
      item: null,
    },
    tabList: [],
    timerObj: { //限时抢购计时器对象
      timer: null,
      isEnd: false,
      endTime: '',
      item: null
    },
    syncTimerObj: { //一直循环的计时器
      timer: null,
      second: 0,
    },
    tabIdList: null, //tab id list二维数组与map互换
    goodsList: [],
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据
    shareInfo: null, //分享信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.timerObj.timer) {
      clearTimeout(this.data.timerObj.timer);
    }
    if (this.data.syncTimerObj.timer) {
      clearTimeout(this.data.syncTimerObj.timer);
    }
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //如果是分享进来的，并且没有选择角色，进入角色选择页面
    if (page_js.pageOptionsInfo()) {
      //2.relauch
      wx.reLaunch({
        url: '../indexSearchShop/indexSearchShop'
      });
    }
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},

  //初始化数据
  initData: function (options) {
    let tempUserInfo = user_js.userInfo();
    if (!user_js.hasRole()) {
      //1.save param
      let obj = {
        url: '../buyLimit/buyLimit',
        param: ''
      }
      page_js.savePageOptionsInfo(obj);
      //2.relauch
      //*********跳转放在onshow
      return;
    } else {
      //有角色，展示页面
      this.initUnShareOptionsData(options);
      //获取远程仓库数据
      this.getRemoteDatas(true);
    }
  },

  //初始化options数据
  initUnShareOptionsData: function (options) {
    //userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo,
      sysInfo: sys_js.systemInfo()
    });
  },

  // 获取数据
  getRemoteDatas: function (withShareInfo) {
    let requestList = [];
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      shopId: this.data.userInfo.ztd.id
    }
    requestList.push(api.wxRequest(url_js.listUrl, data));
    if (withShareInfo) {
      let shareData = {
        cityId: this.data.userInfo.ztd.cityId,
        code: this.data.userInfo.code,
        shopId: this.data.userInfo.ztd.id,
        type: 1
      };
      requestList.push(api.wxRequest(url_js.homeShareConfigUrl, shareData));
    }
    //获取数据
    Promise.all(requestList).then(results => {
      this.handleListData(results[0]);
      if (withShareInfo) {
        this.handleHomeShareConfigData(results[1]);
      }
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的tab数据
  handleListData: function (res) {
    //分享过来，如果当前点位不售卖分享过来的商品，回首页
    if (res.code == 704) {
      wx.switchTab({
        url: '../index/index'
      });
      return;
    }

    //设置数据
    if (res.result.length > 0) {
      let tmpList = res.result;
      let tmpSelctedIndex = this.getTabSelectedIndex(res.result);
      let tmpSelectedItem = tmpList[tmpSelctedIndex];
      //默认选中第一个
      let tmpSelectedInfo = this.data.selectedInfo;
      tmpSelectedInfo.index = tmpSelctedIndex;
      tmpSelectedInfo.item = tmpSelectedItem;
      this.setData({
        contentStatus: 1,
        selectedInfo: tmpSelectedInfo,
        tabList: tmpList
      });

      //执行限时抢购倒计时
      if (tmpSelectedItem.state == 1) {
        this.startLimitTimer(tmpSelectedItem.expire);
      }
      //开始synctimer
      this.countDownSyncTimer();

      //1.请求展示的商品数据
      this.requestToGetlistProduct(tmpSelectedItem.id);
    }
  },

  // 获取默认的选中状态
  getTabSelectedIndex: function (list) {
    let index = 0;
    list.forEach((item, itemIndex) => {
      if (item.selected) {
        index = itemIndex;
        return false;
      }
    });
    return index;
  },

  //处理返回的分享数据
  handleHomeShareConfigData: function (res) {
    this.setData({
      shareInfo: res.result
    });
    //1.开启转发
    wx.showShareMenu({});
  },

  //展示商品数据
  requestToGetlistProduct: function (flashSaleId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      flashSaleId: flashSaleId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.listProductUrl, data).then(res => {
      this.handleListProductData(res, flashSaleId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的商品数据
  handleListProductData: function (res, flashSaleId) {
    let tmpList = res.result;
    //根据id设置数组
    let tmpMap = new Map(this.data.tabIdList);
    if (tmpList.length > 0) {
      tmpMap.set(flashSaleId, tmpList);
    } else {
      tmpMap.set(flashSaleId, []);
    }
    //data
    this.setData({
      goodsList: tmpList,
      tabIdList: [...tmpMap]
    });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = false;
        if (skuItem.userBuyLimit && skuItem.userBuyLimit > 0) {
          isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        }
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //顶部切换
  onseg: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.tabList[index];
    //selectedInfo
    let tmpSelectedInfo = this.data.selectedInfo;
    tmpSelectedInfo.index = index;
    tmpSelectedInfo.item = item;
    //更新计时器----进行中
    if (item.state == 1) {
      if (item.expire - this.data.syncTimerObj.second <= 0) {
        item.state = 2;
        this.setData({
          tabList: this.data.tabIdList
        });
      } else {
        //开始计时器
        this.startLimitTimer(item.expire - this.data.syncTimerObj.second);
      }
    }

    let tmpMap = new Map(this.data.tabIdList);
    if (tmpMap.get(item.id)) {
      let tmpList = tmpMap.get(item.id);
      // set data
      this.setData({
        selectedInfo: tmpSelectedInfo,
        goodsList: tmpList
      });
    } else {
      //set data
      this.setData({
        selectedInfo: tmpSelectedInfo
      });
      //请求数据并展示
      this.requestToGetlistProduct(item.id);
    }
  },

  //添加商品
  onAddGoods: function (e) {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return
    }

    let index = e.currentTarget.dataset.index;
    let item = this.data.goodsList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = false;
        if (skuItem.userBuyLimit && skuItem.userBuyLimit > 0) {
          isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        }
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.buyLimitGoodsAdd);
  },

  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  //商品详情
  onGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.goodsList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    })
  },

  // 同步计时器**********
  countDownSyncTimer() { //倒计时函数
    //定时清除
    clearTimeout(this.data.syncTimerObj.timer);

    let tmpTimerObj = this.data.syncTimerObj;
    tmpTimerObj.second++;

    //1s调用一次
    let that = this;
    let timerItem = setTimeout(function () {
      that.countDownSyncTimer()
    }, 1000);

    tmpTimerObj.timer = timerItem;
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      syncTimerObj: tmpTimerObj
    })
  },
  // 同步计时器**********

  // 开始限时抢购计时器
  startLimitTimer: function (expire) {
    let tmpTimerObj = this.data.timerObj;
    tmpTimerObj.endTime = new Date().getTime() + expire * 1000;
    this.setData({
      timerObj: tmpTimerObj,
    });
    this.countDownLimitTimer();
  },

  // 限时抢购计时器**********
  countDownLimitTimer() { //倒计时函数
    //定时清除
    clearTimeout(this.data.timerObj.timer);

    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let tmpTimerObj = this.data.timerObj;
    let endTime = tmpTimerObj.endTime;
    let time = (endTime - newTime) / 1000;
    // 如果活动未结束，对时间进行处理
    let hmsObj = common_js.getHrMinSecBySecond(time);
    tmpTimerObj.item = hmsObj.item;
    tmpTimerObj.isEnd = hmsObj.isEnd;
    //1s调用一次
    let that = this;
    let timerItem = setTimeout(function () {
      that.countDownLimitTimer()
    }, 1000);

    if (tmpTimerObj.isEnd) {
      clearTimeout(timerItem);
      return;
    } else {
      tmpTimerObj.timer = timerItem;
    }
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      timerObj: tmpTimerObj
    })
  },
  // 限时抢购计时器**********

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.buyLimitShare);

    return this.shareAppMessage();
  },

  //获取分享的AppMessage
  shareAppMessage: function () {
    let tmpPath = '/pages/buyLimit/buyLimit';
    return {
      title: this.data.shareInfo ? this.data.shareInfo.title : '好想你心选',
      path: tmpPath,
      imageUrl: this.data.shareInfo ? this.data.shareInfo.href : ''
    }
  },
})